package com.kitty.game.activity.service.boos.handler;

import com.kitty.common.cache.RedisService;
import com.kitty.common.utils.SpringUtils;
import com.kitty.common.core.SchedulerManager;
import com.kitty.game.activity.model.product.ActivityType;
import com.kitty.game.activity.model.product.SuperBoss;
import com.kitty.game.activity.service.boos.service.BoosService;
import com.kitty.game.activity.service.time.FightActivityHandler;
import com.kitty.game.boss.config.BossSet;
import com.kitty.game.boss.model.BossFightParam;
import com.kitty.game.boss.model.BossParam;
import com.kitty.game.boss.model.SuperBossParam;
import com.kitty.game.boss.model.SuperBossZPParam;
import com.kitty.game.chat.service.ChatService;
import com.kitty.game.common.BoosTitleDeal;
import com.kitty.game.config.NPC;
import com.kitty.game.drop.newservice.NewDropService;
import com.kitty.game.enter.TitleInfo;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.fight.bean.Fight;
import com.kitty.game.fight.bean.FightObject;
import com.kitty.game.fight.service.FightExecutorService;
import com.kitty.game.fight.service.FightService;
import com.kitty.game.rank.message.RespWorldRoleRank;
import com.kitty.game.rank.message.WorldBossRank;
import com.kitty.game.role.model.Role;
import com.kitty.game.team.model.Member;
import com.kitty.game.team.model.Team;
import com.kitty.game.utils.Const;
import com.kitty.listener.event.FightEndEvent;
import com.kitty.mina.message.MessagePusher;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

@Component
@Slf4j
public class DaRiJinWuHandlr extends FightActivityHandler {
    public static AtomicLong dari_life = new AtomicLong();
    public static AtomicLong dari_max_life = new AtomicLong();
    public static Map<String, Long> killWorldBossTime = new ConcurrentHashMap<>();

    private Map<String, SuperBoss> superBossMap = new HashMap<>();
    private static final String boy_name[] = {"金乌之灵","金乌之灵","金乌之灵","金乌之灵"};
    @Autowired
    ChatService chatService;
    @Autowired
    FightService fightService;
    @Autowired
    RedisService redisService;
    @Autowired
    NewDropService newDropService;
    /**
     * 最少组队人数
     */
    private static final int MIN_TEAM_COUNT = 1;
    private static final String TEAM_COUNT_NOT_ENOUGH = "你还是组队后再来向我挑战吧！[离开]";
    private static final int ACCEPT_MIN_LEVEL = 70;
    private static final String TEAM_LEVEL_NOT_ENOUGH = "#Y{0}#n的等级还没有{1}级。[离开]";

    // private static final String [] petArr=new String[]{"百年黑熊","赤血幼猿","玄天刺猬","血幻豪猪"};
    @PostConstruct
    private void init() {

        SuperBoss superBoss = new SuperBoss("大日金乌", 6310, 702);
        superBoss.setSmallBossName("金乌之灵");
        superBoss.getArtifactMap().put("番天印", 24);
        superBoss.getArtifactMap().put("混元金斗", 24);
        superBoss.getArtifactMap().put("定海珠", 6);
        superBoss.getArtifactMap().put("卸甲金葫", 24);
        superBoss.setMainShowAfterRound((byte) 10);
        superBoss.getPolarSmallSkills().put(Const.SCHOOL_METAL,Arrays.asList(11,12,13,14,15,31,32,33,34,35) );
        superBoss.getPolarSmallSkills().put(Const.SCHOOL_WOOD,Arrays.asList(61,62,63,64,65,81,82,83,84,85) );
        superBoss.getPolarSmallSkills().put(Const.SCHOOL_WATER,Arrays.asList(110,111,112,113,114,131,132,133,134,135) );
        superBoss.getPolarSmallSkills().put(Const.SCHOOL_FIRE,Arrays.asList(161,162,163,164,165,181,182,183,184,185) );
        superBoss.getPolarSmallSkills().put(Const.SCHOOL_EARTH,Arrays.asList(210,211,212,213,214,231,232,233,234,235) );
        superBossMap.put(superBoss.getName(), superBoss);
    }


    @Override
    protected String getNpcContent(Role role, NPC bossNpc) {
        return null;
    }

    @Override
    protected String getNpcContentNotFight(Role role, NPC bossNpc) {

        /**检测队伍人数*/
        int teamCount = teamService.getTeamCount(role);
        if (teamCount < MIN_TEAM_COUNT) {
            return TEAM_COUNT_NOT_ENOUGH;
        }

        /**检测等级*/
        Team team = teamService.getTeam(role.getRoleId());
        String names = teamService.checkMember(team, memberRole -> memberRole.getLevel() < ACCEPT_MIN_LEVEL);
        if (names != null) {
            return MessageFormat.format(TEAM_LEVEL_NOT_ENOUGH, names, ACCEPT_MIN_LEVEL);
        }

        names = teamService.checkMember(team, memberRole -> getRoleRemainCount(memberRole) <= 0);

        if (names != null) {
            return "#R" + names + "#n没有挑战次数";
        }
        if (getRoleRemainCount(role) <= 0) {
            return "#R" + role.getName() + "#n没有挑战次数";
        }
        return null;

    }

    private int getRoleRemainCount(Role role) {
        return SpringUtils.getActivityService().getRemainCount(role, ActivityType.darijinwu);
    }

    @Override
    protected void doStartFight(Role role, NPC bossNpc) {
        return;
    }
    public void challenge1(Role role, NPC bossNpc){
        bossNpc.setName("大日金乌");
        /**检测队伍人数*/
        int teamCount = teamService.getTeamCount(role);
        if (teamCount < MIN_TEAM_COUNT) {
            sendNpcContent(role, bossNpc, TEAM_COUNT_NOT_ENOUGH);
            return ;
        }

        /**检测等级*/
        Team team = teamService.getTeam(role.getRoleId());

        String names = teamService.checkMember(team, memberRole -> memberRole.getLevel() < ACCEPT_MIN_LEVEL);

        if (names != null) {
            MessageFormat.format(TEAM_LEVEL_NOT_ENOUGH, names, ACCEPT_MIN_LEVEL);
            return;
        }

        names = teamService.checkMember(team, memberRole -> getRoleRemainCount(memberRole) <= 0);
        if (names != null) {
            sendNpcContent(role, bossNpc, "#R" + names + "#n没有挑战次数");
            return ;
        }
        if (getRoleRemainCount(role) <= 0) {
            sendNpcContent(role, bossNpc,  "#R" + role.getName() + "#n没有挑战次数");
            return ;
        }
        //判断大日金乌 是否在可战斗 时间内。
        String dari_status = redisService.get("dari_status").toString();
        if("1".equals(dari_status)){
            List<BossParam> bossParamList = newBossParamList(role, bossNpc);
            BossFightParam bossFightParam = new BossFightParam(bossParamList, getFightType(role));
            bossFightParam.setNpcId(bossNpc.getId());
            int maxRoleLevel = teamService.getMaxRoleLevelInTeam(role);
            bossFightParam.setNpcLevel((short) maxRoleLevel);
            bossService.startFightToBoss(role, bossFightParam);
        }else{
            sendNpcContent(role, bossNpc,  "未到挑战时间");
            return ;
        }

    }

    /**
     * 获取当前日期是星期几<br>
     *
     * @param dt
     * @return 当前日期是星期几
     */
    public static String getWeekOfDate(Date dt) {
        //String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        String[] weekDays = {"7", "1", "2", "3", "4", "5", "6"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }
    private List<BossParam> newBossParamList(Role role, NPC bossNpc) {
        bossNpc.setName("大日金乌");
        SuperBoss superBoss = getSuperBoss(bossNpc.getName());
        List<BossParam> bossParamList = new ArrayList<>();
        int count = 10;
        SuperBossParam superBossParam = SpringUtils.getBean(BoosService.class).newSuperBossParam(bossNpc,getSuperBoss("大日金乌"));
        superBossParam.setMainShowAfterRound(superBoss.getMainShowAfterRound());
        superBossParam.setSmallEscapeAfterRound(superBoss.getSmallEscapeAfterRound());
        if (superBoss.isSmallPolarRandom()) {
            byte polar = 2;
            superBossParam.setPolar(polar);
        }
        if (superBoss.isSmallSkillRandom()) {
            ArrayList<Integer> skillIds = new ArrayList<>(superBoss.getPolarSmallSkills().get((byte) superBossParam.getPolar()));
            superBossParam.setSkillIds(skillIds);
        }
        bossParamList.add(superBossParam);

        /**加count-1个*/
        int smallCount = superBoss.getZPName() != null ? count - 1 : count;
        for (int i = 1; i < smallCount; i++) {
            int index = (int) (Math.random() * boy_name.length);
            BossSet bossSet = bossService.getBossSet(boy_name[index]);
            BossParam bossParam = new BossParam(bossSet, bossSet.getName());
            if (superBoss.isSmallPolarRandom()) {
                byte polar = SpringUtils.getBean(BoosService.class).getRandomPolar();
                bossParam.setPolar(polar);
            }
            if (superBoss.isSmallSkillRandom()) {
                ArrayList<Integer> skillIds = new ArrayList<>(superBoss.getPolarSmallSkills().get((byte) bossParam.getPolar()));
                bossParam.setSkillIds(skillIds);
            }
            bossParamList.add(bossParam);
        }
        if (superBoss.getZPName() != null) {
            BossSet bossSet = bossService.getBossSet(superBoss.getZPName());
            bossParamList.add(new SuperBossZPParam(bossSet, bossSet.getName()));
        }

        return bossParamList;
    }



    private SuperBoss getSuperBoss(String name) {
        return superBossMap.get(name);
    }

    @Override
    protected int getFightType(Role role) {
        return Const.darijinwu;
    }

    @Override
    protected NPC getBossNpc(int npcId) {
        return SpringUtils.getMapService().getNpc(npcId);
    }

    @Override
    protected void clearNpcAfterWin(Role role, NPC bossNpc) {
        clearNpc(bossNpc);
    }

    private void clearNpc(NPC npc) {
        return;
    }

    @Override
    protected void giveReward(Role role, FightEndEvent fightEndEvent, NPC bossNpc) {
        int count = getRoleRemainCount(role);
        if (count > 0) {/*次数在npc类 这个0只是取数*/
            // 这里改成公共获取配置 经验，道行，武学 奖励。 不再单独写
            fightService.sendBossBasicsReward(role,fightEndEvent);
            SpringUtils.getActivityService().addFinishCount(role, ActivityType.darijinwu, 1);
            //获取道具奖励
            fightService.sendBossExtReward(role,fightEndEvent);
        } else{
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("今日挑战次数以达到上限！不会给奖励"));
            return;
        }
    }

    @Override
    protected void clearNpcTimeOut(NPC npc) {
        clearNpc(npc);
    }

    @Override
    public void doFightFail(Role role, FightEndEvent fightEndEvent) {
        super.doFightFail(role, fightEndEvent);

        teamService.memberHandleThreadLocal(role, memberRole -> SpringUtils.getRoleService().punishFightDead(memberRole));
    }
    /**
     * 首杀BOOS奖励称号
     */
    @Override
    public void doFightWinForTeam(Team team, FightEndEvent fightEndEvent, NPC bossNpc) {
        String dari_status = redisService.get("dari_status").toString();
        if("1".equals(dari_status)){
            String title = "浴火焚神·金乌之灵";
            final Boolean[] flag = {false};
            List<Map<String, String>> list = SpringUtils.getBean(BoosTitleDeal.class).getBossTitleInfo("drjw");
            teamService.memberHandleThreadLocal(team, role -> {
                /**发称号*/
                if (list.size() <= 0) {
                    SpringUtils.getRoleService().addTitle(role, new TitleInfo(title, title));
                    SpringUtils.getBean(BoosTitleDeal.class).addBoosTitle(role.getName(), "drjw", title);
                    flag[0] = true;
                }
                giveReward(role, fightEndEvent, bossNpc);
            });
            // 更新数据库首次称号奖励
            if (flag[0]) {
                sendShouShaReward(team,bossNpc,title);
                SpringUtils.getBean(BoosTitleDeal.class).updateBoosTitle();
            }
            BossSet bossSet = bossService.getBossSet("大日金乌");

            Role leaderRole = SpringUtils.getRoleService().getPlayerBy(team.getLeaderRoleId());
            double randomLife = 1 + (new Random().nextInt(30) + 10) / 100.00;
            int qixue = (int)(bossSet.getQixue() * leaderRole.getLevel()*randomLife);
            //记录一下当前队伍的结束时间，获取排名的时候可以能会使用，
            //暂时先这样 以后在说。
            long systemTime = System.currentTimeMillis();
            for (Member member : team.getList()) {
                killWorldBossTime.put(member.getName(),systemTime);
                Role memberRole = SpringUtils.getRoleService().getPlayerBy(member.getRoleId());
                short oldRank = (short)redisService.find("dariRank",memberRole.getName());
                int newDamage = 0;
                WorldBossRank worldBossRank  = new WorldBossRank();
                worldBossRank.setName(member.getName());
                worldBossRank.setDamage(qixue);
                if(oldRank>0){
                    newDamage = redisService.incrementScore("dariRank", worldBossRank).intValue();
                }else{
                    oldRank = 9999;
                    double rankTime = getRankTime(systemTime);
                    redisService.add("dariRank",member.getName(),qixue+rankTime);
                    newDamage = qixue;
                }

                short newRank = (short)redisService.find("dariRank",memberRole.getName());
                RespWorldRoleRank respWorldRoleRank = new RespWorldRoleRank();
                respWorldRoleRank.setOld_rank(oldRank);
                respWorldRoleRank.setNew_rank(newRank);
                respWorldRoleRank.setAdd_damage(qixue);
                respWorldRoleRank.setNew_damage(newDamage);

                respWorldRoleRank.setInside_rank(newRank);
                MessagePusher.pushMessage(memberRole, respWorldRoleRank);
            }

            long l = dari_life.addAndGet(-qixue);
            if(l <= 0){
                dari_life.set(0);
                //血量为零 表示大日金乌已经被打死了。活动应该结束了。
                endDaRiActivity();
            }
        }
    }

    public void startDaRiActivity(){
        //发送消息
        SchedulerManager.getInstance().schedule(new Runnable() {
            @Override
            public void run() {
                String notice = "#Y大日金乌#n活动已经开始了，请各位道友前往#Y逍遥仙#n选择#R#Z大日金乌#Z#n一起消灭大日金乌，该活动奖励丰富,请积极参与！";
                chatService.sendAdnotice(notice);
            }
        }, 1000);
        //设置大日金乌状态
        redisService.set("dari_status","1");
        //初始化大日金乌血量
        int worldBossLife = Integer.parseInt(redisService.get("dari_life").toString());
        dari_life.set(worldBossLife);
        dari_max_life.set(worldBossLife);
        //清空redis排名数据
        redisService.delAllRank("dariRank");
        //清空 队伍击杀时间数据
        killWorldBossTime.clear();

    }
    public void endDaRiActivity(){
        String currentState = redisService.get("dari_status");
        //多一步 验证， 表示正在开启状态。
        if("1".equals(currentState)){
            redisService.set("dari_status","0");
            //发送消息
            String notice = "#Y大日金乌已离去#n活动已经结束了#Z#n感谢各位道友的参加！";
            chatService.sendAdnotice(notice);
            //结束所有大日金乌的战斗
            quiteFight();
            //结算排名奖励
            sendDariReward();
        }
    }
    //大日金乌结算奖励
    public void sendDariReward(){
        List<WorldBossRank> dariRank = redisService.getRankListType("dariRank");
        for (WorldBossRank worldBossRank : dariRank) {
            short rank = worldBossRank.getRank();
            Role tempRole = SpringUtils.getRoleService().getPlayerBy(worldBossRank.getName());
            String msg = "恭喜#Y" + tempRole.getName() + "#n在大日金乌活动排名第#R" + rank +"#n名，由于您出色的表现获得以下奖励！";
            MessagePusher.pushMessage(tempRole, new RespNotifyMiscEx(msg));
            String reward = redisService.get("dari_rank_" + rank).toString();
            for (String s : reward.split("\\+")) {
                newDropService.addRewardTask(tempRole,s,"");
            }

        }
    }



    //大日金乌退出战斗
    public void quiteFight(){
        ConcurrentHashMap<Integer, Fight> fights = FightExecutorService.FIGHTS;
        FightService bean = SpringUtils.getBean(FightService.class);
        for (Map.Entry<Integer, Fight> integerFightEntry : fights.entrySet()) {
            Fight fight = integerFightEntry.getValue();
            boolean isquite = false;
            try{
                for (FightObject fightObject : fight.getAllFightObjects()) {
                    Role tempRole = fightObject.getRole();

                    if (tempRole == null){
                        break;
                    }
                    //20003
                    if(isInDaRiMap(tempRole)){
                        isquite = true;
                        bean.quiteFight(fight, fightObject, false);
                    }
                }
                if(isquite){
                    bean.clearFight(fight);
                }
            }catch(Exception e){
                log.info("大日金乌结束战斗出错{}",e);
            }
        }
    }
    public boolean isInDaRiMap(Role role) {
        return SpringUtils.getMapService().isInMap(role, 20003);
    }
    public double getRankTime(long time){
        BigDecimal subtract = new BigDecimal("1.0").subtract(new BigDecimal(time * Math.pow(10, Math.negateExact(String.valueOf(time).length()))));
        return subtract.doubleValue();
    }
}
